package com.business_clean.app.uitl;

import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;

import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener;
import com.luck.picture.lib.utils.DateUtils;

import java.io.File;

import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnNewCompressListener;
import top.zibin.luban.OnRenameListener;

/**
 * 鲁班压缩的工具类，根据不同的需求去统一定义
 */
public class ImageCompressor {
    /**
     * 对图片进行压缩
     * 指定压缩的大小
     *
     * @return
     */
    public static void compressBitmap(Context context, String photos, int compressSize, OnKeyValueResultCallbackListener call) {
        Luban.with(context)
                .load(photos)
                .ignoreBy(compressSize)
                .setRenameListener(new OnRenameListener() { //重写名字
                    @Override
                    public String rename(String filePath) {
                        int indexOf = filePath.lastIndexOf(".");
                        String postfix = indexOf != -1 ? filePath.substring(indexOf) : ".jpg";
                        return DateUtils.getCreateFileName("CMP_") + postfix;
                    }
                })
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setCompressListener(new OnNewCompressListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(String source, File compressFile) {
                        if (call != null) {
                            call.onCallback(source, compressFile.getAbsolutePath());
                        }
                    }

                    @Override
                    public void onError(String source, Throwable e) {
                        if (call != null) {
                            call.onCallback(source, null);
                        }
                    }
                }).launch();
    }

}
